package com.whfc.ms.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xugouhceng
 * @desc WebSocket Session管理器
 */
@Component
public class WebSocketSessionManager {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>(128);

    /**
     * 保存用户的websocket连接
     *
     * @param userId
     * @param session
     */
    public void addSession(String userId, WebSocketSession session) {
        WebSocketSession oldSession = sessionMap.put(userId, session);
        logger.info("oldSession:{},newSession:{}", oldSession, session);
    }

    /**
     * 清除用户的websocket连接
     *
     * @param userId
     */
    public void closeSession(String userId) {
        WebSocketSession session = sessionMap.get(userId);
        if (session != null && session.isOpen()) {
            try {
                session.close();
                sessionMap.remove(userId, session);
            } catch (IOException ex) {
                logger.error("close websocket session error!", ex);
            } finally {

            }

        }
    }

    /**
     * 获取用户的websocket连接
     *
     * @param userId
     * @return
     */
    public WebSocketSession getSession(String userId) {
        return sessionMap.get(userId);
    }

    /**
     * 判断session是否有效
     *
     * @param session
     * @return
     */
    public boolean isOnline(WebSocketSession session) {
        return session != null && session.isOpen();
    }
}
